import wx from "weixin-js-sdk";
import axios from 'axios'
import { PAGE_BASE_URL } from "./config";

export async function initJsSDK() {
  try {
    axios({
      method: "get",
      url: `https://zc.oramage.com/wechat/get_jssdk?url=${location.href}`,
      headers: {
        'X-Requested-With': 'xmlhttprequest'   //请求头携带的token
      }
    }).then(res => {
      const { appId, timestamp, nonceStr, signature, jsApiList } = res.data.data;
      wx.config({
        debug: false, // 开启调试模式
        appId, // 必填，公众号的唯一标识
        timestamp, // 必填，生成签名的时间戳
        nonceStr, // 必填，生成签名的随机串
        signature, // 必填，签名，见附录1
        jsApiList: [
          // 必填，需要使用的JS接口列表，见附录2
          "onMenuShareTimeline",
          "onMenuShareAppMessage",
          "onMenuShareQQ",
          "onMenuShareWeibo",
          "onMenuShareQZone",
          "chooseWXPay",
          "getLocation",
          "openLocation",
          "scanQRCode",
          "chooseImage",
          "uploadImage",
          "previewImage",
          "getLocalImgData",
          "startRecord",
          "stopRecord",
          "onVoiceRecordEnd",
          "uploadVoice",
          'wx-open-launch-weapp',
        ],
        openTagList: ["wx-open-launch-weapp"]
      });

      wx.ready(() => {
        setShare({});
      });

      wx.error(res => {
        // console.log("wx.error: ", res);
      })
    })
    //
  } catch (e) {
    // Dialog.confirm({
    //   title: "提示",
    //   message: "微信JSSDK授权失败，这将会影响您的分享及定位操作。是否重试？",
    //   confirmButtonText: "重试"
    // })
    //   .then(() => {
    //     initJsSDK();
    //   })
    //   .catch(() => {
    //     // on cancel
    //   });
  }
}

export function setShare({
  title = "政务走访管理系统", // 分享标题
  desc = "您的好友正在政务走访管理系统，快去看看吧",
  link = window.location.href, // 默认是首页
  imgUrl = PAGE_BASE_URL + "logo2.jpg" // 默认分享图标
}) {
  const infoThunk = str => obj =>
    wx.onMenuShareAppMessage({
      title,
      link,
      imgUrl,
      desc,
      cancel: infoThunk("onMenuShareAppMessage cancel"),
      fail: infoThunk("onMenuShareAppMessage fail"),
      success: infoThunk("onMenuShareAppMessage success")
    });

  wx.onMenuShareTimeline({
    title,
    link,
    imgUrl,
    desc,
    cancel: infoThunk("onMenuShareTimeline cancel"),
    fail: infoThunk("onMenuShareTimeline fail"),
    success: infoThunk("onMenuShareTimeline success")
  });
}
